$m(function (args) {
    var $this = $(this.element).closest("body");
    var testdata = this.data;
    this.jobDialog = null;
    this.flowsParam = {};
    var that = this;
    var service_status;
    flowInfo = {};
    var allDatas = [];
    flows = [];
    var allCount = 0;
    var seleccount = 0;
    var rowDatas = {};
    var successCount = 0;
    var failedCount = 0;
    var nowState = "";
    var runningDatas = [];//已启动的数据集
    var unstartDatas = [];//未启动的数据集
    var startingDatas = [];//启动中的数据集
    var flowIdandStatus = [];//用于从服务详情页面点击返回，页面刷新后的行判断
    // 定义一个判断用户是否点击筛选-查询的标识
    var isSearch = false;
    // 定义一个存储点击筛选-查询时，筛选里所有框的信息
    var searchData = {};
    var alert = function (text) {
        $("<div/>").alert({
            msg: text,
            title: TempoUtils.locale("mine.prompt")
        });
    }

    $this.find("#jobContainer").layout({
        north: {
            resizable: false,
            size: 100,
            spacing_open: 0
        },
        center: {
            onresize: TempoUtils.throttle(function () {
            }, 200, true)
        }
    });


    //列表点击事件
    var syncClickEvent = function () {
        //为筛选按钮添加弹出框事件
        $this.find("#shaixuan").off('click').on('click', function (e) {

            var dialog = $("<div id='shaixuanDailog'></div>");
            //弹出列表进行编辑
            dialog.dialog({
                width: 300,
                height: 300,
                title: "筛选",
                modal: true,
                resizable: "no",
                open: function () {
                    $m.loadHtml(contextPath + "/api/ai/app/statistics/view/dialog", dialog);
                },
                buttons: []
            });
        });
        //为筛选框添加图标提示
        $(".sizer").blur(function () {
            // 获取筛选div里的搜索input框
            var inputs = $('#shaixuanDiv').find('input');
            // 定义是否有数据标识 true表示有数据
            var hasValue = false;
            for (var i = 0; i < inputs.length; i++) {
                if (inputs.eq(i).val().trim() != "") {
                    hasValue = true;
                    break;
                }
            }
            // 如果搜索框中有值，则显示图标
            if (hasValue) {
                $("#ifshaixuan").removeAttr('style');
                $(".sizer-reset").css("color", "#5185e4")
            } else {
                $("#ifshaixuan").hide();
            }
        });
        //为重置按钮添加点击事件
        $("#sizer-reset").click(function () {
            // 将搜索状态改为false，并清空筛选数据
            isSearch = false;
            searchData = {};
            $("#ifshaixuan").hide();
            //将日期选择器清除，并重新初始化
            $("input[name='laststarttime']").datepicker("destroy");
            $("input[name='lastendtime']").datepicker("destroy");
            $(".tempo-sizer-inputright input").val("");
            initOrrefresh(false);
            get_sizerdata(nowState);
        });
        //为暂停按钮添加事件
        $(".tempo-asyn-pause").off('click').on('click', function () {

            pauseJob();
        });
        var bt_starting = $(".tempo-task-starting");
        var bt_complete = $(".tempo-task-complete");
        var bt_unstart = $(".tempo-task-unstart");
        var bt_startsuc = $(".tempo-task-startSucceed");
        //根据点击启动状态按钮改变按钮颜色
        var changeBtColor = function (bt1, bt2, bt3) {
            bt1.css("color", "dimgray");
            bt1.css("background-color", "#eee");
            bt2.css("color", "dimgray");
            bt2.css("background-color", "#eee");
            bt3.css("color", "dimgray");
            bt3.css("background-color", "#eee");
        }
        var getDatabyState = function (status) {
            that.grid.datagrid('reloadGrid', {status: status});
        }
        //为已启动的按钮添加点击筛选条件
        $("#tempo-asyn-runningbt").off('click').on('click', function () {
            nowState = "running";
            runningDatas = [];
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_starting, bt_complete, bt_unstart);
            getDatabyState("running");
        });
        //为启动中按钮添加筛选事件
        $(".tempo-task-starting").off('click').on('click', function () {
            nowState = "starting";
            startingDatas = [];
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_startsuc, bt_complete, bt_unstart);
            getDatabyState("starting");
        });


        //为未启动的按钮添加点击筛选条件
        $("#tempo-asyn-unrunbt").off('click').on('click', function () {
            nowState = "unstart";
            unstartDatas = [];
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_startsuc, bt_complete, bt_starting);
            getDatabyState("unstart");
        });
        //为“全部”按钮绑定筛选条件
        $("#tempo-asyn-allbt").off('click').on('click', function () {
            nowState = "all";
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_startsuc, bt_unstart, bt_starting);
            //that.grid.datagrid("clearGridData");
            getDatabyState("all");
            // $(".ui-common-table").css("width", "100%");
        });
        //点击取消发布，删除本条监测信息方法
        $(".tempo-sync-unpublish").off('click').on('click', function (e) {
            var id = $(this).attr('serviceId');
            var flowObjectid = $(this).attr('flowObjectid');
            $('<div/>').confirm({
                msg: "是否确认取消发布？",
                ok: function () {
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/app/unpublish",
                        data: {
                            id: flowObjectid,
                            flowObjectId: id
                        },
                        dataType: 'json',
                        type: 'post',
                        traditional: true,
                        success: function (result) {
                            progressbar.tempoprogressbar("destroy");
                            if (result.success) {
                                $this.find('.cglist-view-container').empty();
                                $m.loadPage(contextPath + "/api/ai/app/schedule/view/synchronize_server", $this.find('.cglist-view-container'));
                                nowSizerStatus();
                            } else {
                                if (result.messageCode === "gray") {
                                    TempoUtils.showTip("服务已灰度发布,不可取消发布");
                                } else {
                                    TempoUtils.showTip("取消失败！服务为已启动状态，不允许取消发布。");
                                }
                            }
                        },
                        error: function (e) {
                            progressbar.tempoprogressbar("destroy");
                            nowSizerStatus();
                        }
                    });
                }
            });

        });
        //批量取消发布
        $(".tempo-batch-unpublish").off('click').on('click', function (e) {
            var allselectDatas = that.grid.datagrid("getSelectRowData");
            var rowIds = that.grid.datagrid("getSelectRowIds");
            var idList = [];
            var flowObjectIdList = [];
            for (var i = 0; i < rowIds.length; i++) {
                //之前id传入有误，导致传入后台接口查询parentId为空
                idList.push(allselectDatas[i].SERVICEFLOWID);
                flowObjectIdList.push(allselectDatas[i].SERVICEID);
            }
            if (idList.length == 0) {
                alert("服务列表为空！");
                return;
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + rowIds.length + "个任务，是否确定批量取消发布？",
                ok: function () {
                    var process = $("<div/>").tempoprogressbar();
                    $(".after_select").hide();
                    $.ajax({
                        url: contextPath + '/api/ai/app/batch-unpublish',
                        type: 'post',
                        traditional: true,
                        data: {
                            id: idList,
                            flowObjectId: flowObjectIdList
                        },
                        success: function (rs) {
                            process.tempoprogressbar("destroy");
                            if (rs.success) {
                                $this.find('.cglist-view-container').empty();
                                $m.loadPage(contextPath + "/api/ai/app/schedule/view/synchronize_server", $this.find('.cglist-view-container'));
                                nowSizerStatus();
                            } else {
                                if (rs.messageCode === "gray") {
                                    TempoUtils.showTip("存在流程被灰度发布,不可取消发布");
                                } else {
                                    nowSizerStatus();
                                    TempoUtils.showTip("取消失败！" + rs.message);
                                }
                            }
                        },
                        error: function (e) {
                            process.tempoprogressbar("destroy");
                            nowSizerStatus();
                        }
                    });

                }
            });

        });
        var get_sizerdata = function (statasParam) {
            var publishtime_pre = $("input[name='laststarttime']").datepicker('getDate');
            var publishtime_end = $("input[name='lastendtime']").datepicker('getDate');
            var sizer_data = {
                serverName: $("input[name='serveName']").val().trim(),
                workspaceName: $("input[name='workspaceName']").val().trim(),
                applicationName: $("input[name='applicationName']").val().trim(),
                jobcreator: $("input[name='jobcreator']").val().trim(),
                publishtime_pre: publishtime_pre ? DateUtils.formatDate(publishtime_pre, 'yyyy-MM-dd') : null,
                publishtime_end: publishtime_end ? DateUtils.formatDate(publishtime_end, 'yyyy-MM-dd') : null,
                status: statasParam
            };
            searchData = sizer_data;
            that.grid.datagrid("reloadGrid", sizer_data);
        }
        //筛选框查询事件
        $(".queryBtn").off('click').on('click', function () {
            $("#shaixuanDiv").hide();
            isSearch = true;
            get_sizerdata(nowState);

        });
    }

    var getFlowParams = function (type, paramValueInput, value, nodeType) {
        var pss = [];
        if (type == 'datasource') {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/node/io/list-datasources',
                type: 'post',
                success: function (rs) {
                    process.tempoprogressbar("destroy");
                    var data = rs.data;
                    var itemHtml = [];
                    for (var i = 0; i < data.length; i++) {
                        var dataItem = data[i];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if(nodeType == 'writehive'){
                            if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if( nodeType == "readiotdb"){
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if( nodeType == "writeiotdb"){
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = itemHtml.join('');
                    paramValueInput.html(html);
                    paramValueInput.selectmenu({
                        editable: false,
                        width: 150,
                        labelForTitle: true
                    }).selectmenu('setValue', value).selectmenu('refresh');
                }
            });
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if (items) {
                for (name in items) {
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }
            var html = pss.join('');
            paramValueInput.html(html);
            paramValueInput.selectmenu({
                editable: true,
                width: 150,
                labelForTitle: true
            }).selectmenu('setValue', value);
        }

    }


    /**
     * 时间切换方法
     */
    var switchShowItem = function (dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
        var _onoff = $.fn.onoff;
        $.fn.onoff = function (value) {
            var element = $(this);
            if (value) {
                element.show();
            } else {
                element.hide();
            }
            element.find('input').each(function (index, ele) {
                var role = $(ele).attr('ui-role');
                if (role == 'validatebox' || role == 'numberbox') {
                    !value ? $(ele)[role]('disable') : $(ele)[role]('enable');
                }
            });
        }
        dialog.find('.times-row').onoff(timesRow);
        dialog.find('.times-board').empty();
        if (timeRange) {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: true}).validatebox('validate');
        } else {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: false}).validatebox('validate');
        }
        dialog.find('.day-of-time-range-row').onoff(timeRange);
        dialog.find('.day-of-time-row').onoff(dayTime);
        dialog.find('.time-interval-row').onoff(interval);
        if (interval && dayMonthYear != undefined) {
            dialog.find('.time-of-day').onoff(dayMonthYear == 1);
            dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
            dialog.find('.day-of-month').onoff(dayMonthYear == 2);
            dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
            dialog.find('.month-of-year').onoff(dayMonthYear == 3);
            dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
        }
        $.fn.onoff = _onoff;
    }

    /**
     * 构建周页面
     */
    var buildWeeks = function (dialog) {
        var board = dialog.find('.times-board');
        var weeks = [2, 3, 4, 5, 6, 7, 1];
        var weekName = [TempoUtils.locale("mine.xinqiyi"),
            TempoUtils.locale("mine.xinqier"),
            TempoUtils.locale("mine.xinqisan"),
            TempoUtils.locale("mine.xinqisi"),
            TempoUtils.locale("mine.xinqiwu"),
            TempoUtils.locale("mine.xinqiliu"),
            TempoUtils.locale("mine.xinqitian")
        ];
        weeks.forEach(function (e, i) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
            $("<label/>").text(weekName[i]).appendTo(span);
        });
        TempoUtils.parserUi(board, {});
    };

    /**
     * 构建天页面
     */
    var buildDays = function (dialog) {
        var board = dialog.find('.times-board');
        for (var i = 1; i <= 31; i++) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
                .val(i)
                .addClass('day-of-month-' + i)
                .appendTo(span);
            $("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
        }
        var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
        $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
            .val("L")
            .addClass('day-of-month-L')
            .appendTo(lastSpan);
        $("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
        TempoUtils.parserUi(board, {});
    }

    /*
     * 判断当前选中的是在哪种筛选状态下
     */
    var nowSizerStatus = function () {
        if (nowState == 'running') {
            $("#tempo-asyn-runningbt").trigger('click')
        } else if (nowState == 'starting') {
            $(".tempo-task-starting").trigger('click');
        } else if (nowState == 'unstart') {
            $("#tempo-asyn-unrunbt").trigger('click');
        } else if (nowState == "all") {
            $("#tempo-asyn-allbt").trigger('click');

        } else {
            $("#tempo-asyn-allbt").trigger('click');
        }
    }

    /**
     * 列表事件
     */
    var bindJobGridEvent = function () {
        var grid = $this.find('#mine-opt-job-grid');

        grid.find(".edit-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            editJob.apply(that, [row]);
        });
        grid.find(".run-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            runJob(row);
        });
        grid.find(".stop-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            stopJob(row, function () {
                grid.jqGrid().trigger("reloadGrid");
            });
        });
        grid.find(".del-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var row = grid.jqGrid("getRowData", rowid);
            deleteJob(row);
        });

        grid.find(".log-job-btn").unbind("click").bind("click", function (e) {
            e.stopPropagation();
            var rowid = $(e.target).attr('rowid');
            var log = $(e.target).attr('logid');
            var runResult = $(e.target).attr('runResult');
            var row = grid.jqGrid("getRowData", rowid);
            downloadLog(row.id, log, runResult);
        });
        grid.find(".viewlog").each(function () {
            var rowid = $(this).attr('rowid');
            var row = null;
            var rows = grid.data('rows');
            if (rows && rows.length > 0) {
                for (var m = 0; m < rows.length; m++) {
                    if (rowid == rows[m].id) {
                        row = rows[m];
                    }
                }
            }
            var logs = row.logs;
            var content;
            if (logs && logs.length > 0) {
                var logele = $('<ul>').css({
                    'list-style-type': 'none'
                });
                for (var i = 0; i < logs.length; i++) {
                    var log = logs[i];
                    var date = new Date(parseFloat(log.runTime));
                    var runResult = log.runResult;
                    var icon = "ui-icon ui-icon-document";
                    if (runResult != null) {
                        if (runResult == 0) {
                            icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
                        } else if (runResult == 1) {
                            icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
                        }
                    }
                    var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
                    var liele = $('<li class="logitem">').attr('jobid', rowid).attr('logid', log.id).attr('runResult', log.runResult).attr('name', logName);
                    var liicon = $("<span>").addClass(icon).appendTo(liele);
                    var lilabel = $("<label>").text(logName).appendTo(liele);
                    logele.append(liele);
                }
                content = $('<div>').append(logele).html();
            }
            var height = 'auto';
            if (logs && logs.length > 0 && logs.length > 5) {
                height = 100;
            } else if (logs && logs.length > 0 && logs.length <= 5) {
                height = logs.length * 20;
            }
            $(this).webuiPopover({
                trigger: 'hover',
                title: '',
                cache: false,
                placement: 'right',
                width: 195,
                height: height,
                closeable: false,
                arrow: true,
                content: content
            });
            $(this).on('shown.webui.popover', function () {
                $('.logitem').each(function (index, domEle) {
                    $(domEle).off('click').on('click', function () {
                        var jobid = $(this).attr('jobid');
                        var logid = $(this).attr('logid');
                        var runResult = $(this).attr('runResult');
                        var name = $(this).attr('name');
                        downloadLog(jobid, logid, name, runResult);
                    })
                });
            });
        });
        //点击服务名称，跳转任务详情界面
        grid.find('.tempo-datagrid-trigger-name').off('click').on("click", function (e) {
            flowIdandStatus = [];
            var rowid = $(e.target).attr('rowid');
            var flowid = $(e.target).attr('flowId');
            window.syncServiceRowId = flowid;
            flowIdandStatus = [];
            var row = rowDatas[flowid];

            var oldStatus = row.ASY_SERVIECESTATE;
            flowIdandStatus.push(flowid);
            flowIdandStatus.push(oldStatus);
            td = $(e.target).attr('rowid');
            //var row = grid.datagrid('getRowData', rowid);
            viewDetail(row);
        })
        //点击测试，触发手动执行方法
        grid.find('.tempo-test').off('click').on("click", function (e) {
            var rowid = $(e.target).attr('rowid');
            var row = rowDatas[rowid];
            manualJob(row);
        })
        grid.find(".tempo-asy-more").off('click').on('click', function (e) {
            var moreDiv = $("#tempo-more");
            moreDiv.find("a").attr("rowId", $(this).attr("rowId"));
            moreDiv.css("display", "");
            moreDiv.mouseleave(function () {
                moreDiv.hide();
            });
            var mousex = e.pageX;
            var mousey = e.pageY;
            moreDiv.css("left", mousex + 18);
            moreDiv.css("top", mousey);
        });

        //点击取消分享，触发删除本条监测信息方法
        $('.tempo-stopShare').off('click').on("click", function (e) {
            var rowid = $(this).attr('rowid');
            var row = rowDatas[rowid];

            $('<div/>').confirm({
                msg: "是否确认取消分享？",
                ok: function () {
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.post(contextPath + "/api/ai/app/category/delete", {
                        "id": row.CATEGORYID,
                        type: 'warehouse'
                    }, function (rs) {
                        console.log(rowid);
                        progressbar.tempoprogressbar("destroy");
                        if (rs.success) {
                            $this.find('.cglist-view-container').empty();
                            $m.loadPage(contextPath + "/api/ai/app/schedule/view/synchronize_server", $this.find('.cglist-view-container'));
                            nowSizerStatus();
                        } else {
                            TempoUtils.showTip("");
                        }
                    });
                    that.grid.jqGrid().trigger("reloadGrid");
                }

            });


        });

        var asyncEnableOrDisabled = function (serviceId, flag) {
            $.ajax({
                url: contextPath + '/api/ai/mine/publish/async-enable',
                type: 'post',
                data: {
                    id: serviceId,
                    flag: flag
                },
            })
            that.grid.jqGrid().trigger("reloadGrid");
        }
        //异步服务停用和停用
        grid.find('.tempo-asyn-start').off('click').on("click", function (job, e) {
            var serviceId = $(this).attr('serviceId');
            asyncEnableOrDisabled(serviceId, "true");
        });
        grid.find('.tempo-asyn-stop').off('click').on("click", function (job, e) {
            var serviceId = $(this).attr('serviceId');
            asyncEnableOrDisabled(serviceId, "false");
        });

        //批量取消分享成果
        $('.tempo-batchDeleteCategory').off('click').on("click", function (e) {

            var allselectDatas = that.grid.datagrid("getSelectRowData");
            var rowIds = that.grid.datagrid("getSelectRowIds");
            var categoryidList = [];
            for (var i = 0; i < rowIds.length; i++) {
                categoryidList.push(allselectDatas[i].CATEGORYID);
            }

            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + rowIds.length + "个任务，是否确定批量取消分享？",
                ok: function () {
                    $(".after_select").hide();
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + '/api/ai/app/category/batchDelete',
                        type: 'post',
                        data: {
                            ids: categoryidList.toString(),
                            type: 'warehouse'
                        },
                        success: function (obj) {
                            process.tempoprogressbar("destroy");
                            $this.find('.cglist-view-container').empty();
                            $m.loadPage(contextPath + "/api/ai/app/schedule/view/synchronize_server", $this.find('.cglist-view-container'));
                            nowSizerStatus();
                            //that.grid.jqGrid().trigger("reloadGrid");
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                            // $(".ui-common-table").css("width", "100%");
                        }
                    });

                }
            });
        });
        //点击暂停按钮，执行任务暂停操作
        grid.find('span[name=runStatus]').off('click').on("click", function (e) {
            var rowid = $(e.target).attr('rowid');
            var row = rowDatas[rowid];
            pauseJob(row);
        });

    }

    /**
     * 下载任务日志
     */
    var downloadLog = function (id, log, name, runResult) {
        TempoUtils.downLoadFile({
            url: contextPath + "/api/ai/mine/publish/downloadJobLog",
            data: {
                id: id,
                name: name,
                log: log,
                runResult: runResult
            }
        });
    }

    var viewDetail = function (job) {
        openViewDetailDialog(job);
    }
    var sizerDivShow = function (one) {
        $("#shaixuanDiv").slideToggle();
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest(one).length == 0) {
                $("#shaixuanDiv").hide();
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                $(document).off('click');
            }
        });
    }
    //筛选框弹出事件绑定
    $("#shaix").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next ");
    });
    //筛选图标点击事件
    $(".tempo-sizer-icon").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next ");
    });
    //当成功失败次数太多时显示不下，因此根据数量扩展外层div大小
    var extendDiv = function (num, object) {

        var oldWidth = object.width();
        if (num >= 100000 && num < 1000000) {
            object.css("width", oldWidth + 20);
        } else if (num >= 1000000) {
            object.css("width", oldWidth + 40);
        }
    }

    /**
     * 初始化列表
     */
    var initJobGrid = function () {
        $(".ui-jqgrid-htable ").css("width", "100%");
        that.grid = $this.find('#mine-opt-job-grid').datagrid({
            datatype: "json",
            url: contextPath + '/api/ai/mine/publish/sync-data-job',
            postData: {},
            fit: true,
            autowidth: true,
            mtype: 'POST',
            rownumbers: true,
            shrinkToFit: true,
            viewrecords: true,
            showRefreshBth: true,//是否显示刷新按钮
            pagination: true,
            striped: true,
            multiselect: true,
            //勾选后的触发事件
            onSelectRow: function () {
                var selecspan = $(".selectedSpan");
                var grid = $this.find('#mine-opt-job-grid');
                var selected = grid.datagrid("getSelectRowIds");
                $(".tempo-datagrid-trigger-name").css("color", "black");
                seleccount = selected.length;
                if (seleccount != 0) {
                    selecspan.text("已选择" + " " + seleccount + " " + "条");
                }
                $(".after_select").css("display", "");
                if (seleccount == 0) {
                    $(".after_select").css("display", "none");
                }
                //全选按钮是否选中
                if (that.grid.find("input").length == seleccount) {
                    that.grid.parent().parent().parent().find("input[id$='_mine-opt-job-grid']").prop("checked", true);
                }
            },
            colNames: ['id',
                'serviceFlowId',
                'jobId',
                'categoryId',
                'serviceId',
                'resourceId',
                '服务名称',
                '所属空间',
                '所属应用',
                '发布人',
                '发布时间',
                //TempoUtils.locale("mine.publish-mine-job-grid-col-lasttime"),//'上次执行时间'
                TempoUtils.locale("mine.publish-mine-job-grid-col-lastcosttime"),//'上一次执行耗时'
                '服务状态',
                // TempoUtils.locale("mine.shangcizhixingjieguo"),
                // TempoUtils.locale("mine.publish-mine-job-grid-col-nexttime"),//'下一次执行时间'
                // TempoUtils.locale("mine.publish-mine-job-grid-col-relatedflow"),//'涉及流程'
                // TempoUtils.locale("mine.publish-mine-job-grid-col-log"),//'日志'
                TempoUtils.locale("mine.zhixingqingkuang"),
                TempoUtils.locale("mine.publish-mine-job-grid-col-opt")//'操作'
            ],
            colModel: [{
                name: 'id',
                hidden: true
            }, {
                name: 'SERVICEFLOWID',
                hidden: true,
                width: 8
            },{
                name: 'jobid',
                hidden: true
            }, {
                name: "CATEGORYID",
                hidden: true,

            }, {
                name: "SERVICEID",
                hidden: true
            }, {
                name: "RESOURCEID",
                hidden: true
            }, {
                name: 'SERVENAME',
                hidden: false,
                sortable: false,

                formatter: function (obj, rows, grid) {
                    rowDatas[grid.CATEGORYID] = grid;
                    var maxWidth = '170px';
                    if (window.screen.width == 1366) {
                        maxWidth = '100px';
                    } else if (window.screen.width == 1600) {
                        maxWidth = '140px';
                    }
                    if (grid.FLOWTYPE == "plflow") {
                        var imgPath = contextPath + "/css/images/pl_icon.png";
                        var html = "<span style='display: inline-flex;overflow: hidden;max-width: " + maxWidth + ";'><a href='javascript:void(0);' class='tempo-datagrid-trigger-name' style='text-decoration: none' rowid='" + rows.rowId + "'flowId='" + grid.FLOWID + "'>" + TempoMineUtils.encodeHTML(obj) + "</a></span>";
                        var plImg = "<img style=' margin-left: 4px;margin-top: 2px;position: absolute;' src='" + imgPath + "'  class='tempo-cggl-sync-service-pl-image'/>";
                        html += plImg;
                    } else {
                        var html = "<span style='display: inline-flex;overflow: hidden;max-width: " + maxWidth + ";'><a href='javascript:void(0);' class='tempo-datagrid-trigger-name' style='text-decoration: none' rowid='" + rows.rowId + "'flowId='" + grid.FLOWID + "'>" + TempoMineUtils.encodeHTML(obj) + "</a></span>"
                    }
                    return html;
                }
            }, {
                name: 'WORKSPACENAME',//所属空间
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    if (obj == null) {
                        return "";
                    }
                    return obj.replace(/</g, "&lt;").replace(/>/g, '&gt;');
                }
            }, {
                name: 'APPLICATION',//所属应用
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    return obj.replace(/</g, "&lt;").replace(/>/g, '&gt;');
                }
            }, {
                name: 'CREATOR',//发布人

                sortable: false,
                sortable: false
            }, {
                name: 'CREATETIME',//发布时间
                hidden: false,
                sortable: true,
                align: "center",
                formatter: function (obj) {

                    if (obj) {
                        return DateUtils.formatDate(new Date(obj), "yyyy-MM-dd HH:mm:ss");
                    }
                    return;
                }

            }, {
                name: 'SPENDTIME',//上次执行耗时
                align: 'center',

                resizable: false,
                sortable: false,

            }, {
                name: 'ASY_SERVIECESTATE',//执行状态
                index: '',
                hidden: false,
                sortable: false,
                formatter: function (obj, grid, rows) {

                    var rowid = rows.SERVICEID;
                    isAlive(rowid);
                    service_status = rowDatas[rowid].ASY_SERVIECESTATE;
                    if (service_status == 'RUNNING') {
                        return '<span class="running" style="color:rgba(0, 148, 240, 1) ">已启动</span>';

                    } else if (service_status == "STARTING") {
                        return '<span class="starting" style="color:rgba(0, 148, 240, 1) ">启动中</span>';
                    } else {
                        return '<span class="unrunning" style="color: dimgrey">未启动</span>';
                    }
                }

            }, {
                title: false,
                name: 'CTYPE',
                index: 'NAME',
                sortable: false,
                formatter: function (obj, grid, rows, state) {
                    var success = rows.successCount || 0;
                    var fail = rows.failedCount || 0;
                    var successNum = success > 100 ? success.toString().substr(0, 2) + "." : success;
                    var failNum = fail > 100 ? fail.toString().substr(0, 2) + "." : fail;
                    return "<button class='state_succ_bt' title='成功" + success + "' style='width: 50px;height: 20px;color:#5185e4;background-color: white;border:1px solid #5185e4;border-radius: 15px;'>" + "成功" + successNum + "</button>" +
                        "<button class='state_fail_bt' title='失败" + fail + "' style='width: 50px;height: 20px;color:#fc7f7f;background-color: white;border:1px solid #fc7f7f;border-radius: 15px;margin-left: 5px;'>" + "失败" + failNum + "</button>";
                }
            }, {
                name: 'rows',
                index: 'NAME',
                sortable: false,

                formatter: function (obj, row, grid, state) {
                    var btn = {};
                    var rowid = grid.SERVICEID;
                    var flowObjectid = grid.SERVICEFLOWID;
                    service_status = rowDatas[rowid].RUNNING_STATUS;
                    var html = "<span ><a id='tempo-sync-unpublish' class='tempo-sync-unpublish tempo-do' href='javascript:void(0)' style='line-height: 30px;color: #2E90E3;text-decoration: none' title='取消发布' serviceId='" + rowid + "' flowObjectid='" + flowObjectid + "'>" + "取消发布" + "</a></span>";
                    return html;
                }
            }
            ],
            loadComplete: function (datas) {
                //解决问题：39697 微服务-挖掘-外网UAT-成果管理：主版本 1点击异步服务的筛选按钮，输入内容之后，筛选符号向上，点击同步服务时，筛选按钮也变成了向上
                $this.find(".tempo-sizer-icon").removeClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
                $this.find(".tempo-sizer-icon").addClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                $(".ui-state-default").css("padding-left", "0px");
                $(".ui-state-default").css("padding-right", "0px");
                // $(".ui-jqgrid-htable ").css("width","100%");
                $(".after_select").hide();
                var startSucCount = 0;
                var startFailcount = 0;
                var runningSucCount = 0;
                var runningFailCount = 0;
                var stopSucCout = 0;
                var stopFailCount = 0;
                var allSuccCount = 0;
                var allFailCount = 0;
                var newData = [];
                var flowid = flowIdandStatus[0];//当前点击服务名称的flowid

                var searchDataTmp = {};
                if (isSearch) {
                    searchDataTmp = searchData;
                    searchDataTmp.status = "";
                    searchDataTmp.sidx = "";
                    searchDataTmp.sord = "";
                } else {
                    searchDataTmp = {
                        serverName: "",
                        workspaceName: "",
                        applicationName: "",
                        jobcreator: "",
                        publishtime_pre: null,
                        publishtime_end: null,
                        status: "",
                        sidx: "",
                        sord: "",
                    };
                }
                $.ajax({
                    url: contextPath + "/api/ai/mine/publish/sync-data-job",
                    type: 'post',
                    data: searchDataTmp,
                    success: function (results) {
                        var rows = results.rows;
                        allDatas = results.rows;
                        for (var i = 0; i < rows.length; i++) {
                            if (flowid == rows[i].FLOWID) {
                                var status = rows[i].ASY_SERVIECESTATE;
                                setTimeout(function () {
                                    if (status == 'STARTING') {
                                        setTimeout(function () {
                                            that.grid.datagrid("reloadGrid");
                                        }, 2000);
                                    } else {
                                    }
                                }, 2000)
                            }
                        }
                        for (i = 0; i < rows.length; i++) {
                            if (rows[i].ASY_SERVIECESTATE == "RUNNING") {
                                if (rows[i].successCount != undefined) {
                                    runningSucCount += rows[i].successCount;
                                    runningFailCount += rows[i].failedCount;
                                    newData.push(rows[i]);
                                } else {
                                    runningSucCount += 0;
                                    runningFailCount += 0;
                                }
                            } else if (rows[i].ASY_SERVIECESTATE == "NONE" || rows[i].ASY_SERVIECESTATE == null) {
                                if (rows[i].successCount != undefined) {
                                    stopSucCout += rows[i].successCount;
                                    stopFailCount += rows[i].failedCount;
                                    newData.push(rows[i]);
                                } else {
                                    stopSucCout += 0;
                                    stopFailCount += 0;
                                }
                            } else if (rows[i].ASY_SERVIECESTATE == "STARTING") {
                                if (rows[i].successCount != undefined) {
                                    startSucCount += rows[i].successCount;
                                    startFailcount += rows[i].failedCount;
                                    newData.push(rows[i]);
                                } else {
                                    startSucCount += 0;
                                    startFailcount += 0;
                                }
                            }

                        }
                        allSuccCount = stopSucCout + startSucCount + runningSucCount;
                        allFailCount = stopFailCount + startFailcount + runningFailCount;
                        if ("running" == nowState) {
                            $(".tempo-task-succeed").val("成功" + runningSucCount);
                            $(".tempo-task-failed").val("失败" + runningFailCount);
                            extendDiv(runningSucCount, $(".tempo-task-succeed"));
                            extendDiv(runningFailCount, $(".tempo-task-failed"));

                        } else if ("starting" == nowState) {
                            $(".tempo-task-succeed").val("成功" + startSucCount);
                            $(".tempo-task-failed").val("失败" + startFailcount);
                            extendDiv(startSucCount, $(".tempo-task-succeed"));
                            extendDiv(startFailcount, $(".tempo-task-failed"));
                        } else if ("unstart" == nowState) {
                            $(".tempo-task-succeed").val("成功" + stopSucCout);
                            $(".tempo-task-failed").val("失败" + stopFailCount);
                            extendDiv(stopSucCout, $(".tempo-task-succeed"));
                            extendDiv(stopFailCount, $(".tempo-task-failed"));
                        } else {
                            $(".tempo-task-succeed").val("成功" + allSuccCount);
                            $(".tempo-task-failed").val("失败" + allFailCount);
                            extendDiv(allSuccCount, $(".tempo-task-succeed"));
                            extendDiv(allFailCount, $(".tempo-task-failed"));
                        }
                        $("#jqgh_mine-opt-job-grid_cb").css("padding-left", "12px");
                        $("#jqgh_mine-opt-job-grid_cb").parent().css("width", "35px");

                        $(this).data('rows', rows);
                        updatestaticsInfo(rows);
                        bindJobGridEvent.apply(that);
                        syncClickEvent();

                    }


                });
                if (datas.rows.length > 0) {
                    $(".tempo-message").css("display", "none");
                    $('#jobContainer').find('.ui-paging-info').show()
                } else {
                    $('#jobContainer').find('.ui-paging-info').hide();
                    $(".tempo-message").css("display", "");
                    if (nowState == "running") {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (nowState == "starting") {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (nowState == "unstart") {
                        $(".tempo-message").children().html("暂无数据");
                    } else {
                        $(".tempo-message").children().html("暂无数据,请在设计区进行流程发布");
                    }
                }
                var browser = $.support.clearCloneStyle;
                var screenWidth = screen.width;
                if (browser) {
                    $this.find("input.tempo-checkbox+label").css("font-size", "12px");
                } else {
                    if (screenWidth == 1366) {
                        //解决IE11下复选框过大问题
                        $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                    }
                }
                //判断浏览器是否为ie浏览器
                if ((TempoUtils.isIE()) && screenWidth == 1366) {
                    //解决IE11下复选框过大问题
                    $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                }
                //解决1366分辨率下ie11下表格显示一条黑线问题
                $this.find(".ui-jqgrid-hdiv").css("height", "38px");
                if (navigator.userAgent.indexOf("Firefox") >= 0) {
                    $this.find(".ui-jqgrid-hdiv").css("border-bottom", "0px solid #eee");
                } else {
                    $this.find(".ui-jqgrid-hdiv").css("border-bottom", "1px solid #eee");
                }
            },
            loadError: function () {
                nowSizerStatus();
            },
            beforeRequest: function () {
                //$(".ui-common-table").css("width","100%");
                var current_page = $(this).getGridParam("page");//获取要请求的页
                var total_page = $(this).getGridParam("lastpage");//获取总页数
                var cont_page = allDatas.length / $(this).getGridParam("rowNum") + 1;
                if (total_page != 0 && current_page > cont_page) {
                    //当输入页码大于总页码时，加载到最后一页
                    that.grid.datagrid("reloadGridToLastPage", {}, true, true, total_page);

                }
            },
            onSelectAll: function (rowids, status) {
                console.log("fsdfsd");

                var multiselect = that.grid.jqGrid().getGridParam("multiselect");
                var rowIds = that.grid.datagrid("getSelectRowIds");
                $(".tempo-datagrid-trigger-name").css("color", "black");
                $(".selectedSpan").text("已选择 " + rowIds.length + " 条");
                if (multiselect && status) {
                    that.grid.jqGrid()
                    $this.find(".after_select").show();
                } else {
                    $this.find(".after_select").hide();
                }
                //批量取消分享成果
                $('.tempo-batchDeleteCategory').off('click').on("click", function (e) {
                    var allselectDatas = that.grid.datagrid("getSelectRowData");
                    var categoryidList = [];
                    for (var i = 0; i < rowIds.length; i++) {
                        categoryidList.push(allselectDatas[i].CATEGORYID);
                    }
                    $("<div>").confirm({
                        width: 500,
                        height: 197,
                        msg: "已选中" + rowIds.length + "个任务，是否确定批量取消分享？",
                        ok: function () {
                            $(".after_select").hide();
                            var process = $("<div/>").tempoprogressbar();
                            $.ajax({
                                url: contextPath + '/api/ai/app/category/batchDelete',
                                type: 'post',
                                data: {
                                    ids: categoryidList.toString(),
                                    type: 'warehouse'
                                },
                                success: function (obj) {
                                    process.tempoprogressbar("destroy");
                                    $this.find(".after_select").hide();
                                    $this.find('.cglist-view-container').empty();
                                    $m.loadPage(contextPath + "/api/ai/app/schedule/view/synchronize_server", $this.find('.cglist-view-container'));
                                    nowSizerStatus();
                                }, error: function (obj) {
                                    process.tempoprogressbar("destroy");
                                    that.grid.jqGrid().trigger("reloadGrid");
                                }
                            });


                        }
                    });
                });
            }
        });
    }
    //筛选框位置计算
    var sxtop = $("#shaix").offset().top;
    var sxleft = $("#shaix").offset().left;
    console.log("横坐标" + sxtop);
    $("#shaixuanDiv").css("top", sxtop + 30);
    $("#shaixuanDiv").css("left", sxleft - 360);
    var updatestaticsInfo = function (rows) {
        failedCount = 0;
        successCount = 0;
        var waiteCount = 0;
        var awaitCount = 0;
        var pauseCount = 0;
        var completeCount = 0;
        if (rows && rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
                var jobInfo = rows[i];
                var trigger = jobInfo.trigger;
                if (trigger) {
                    if ("PAUSED" == trigger.status || "PAUSED_BLOCKED" == trigger.status) {
                        pauseCount++;
                    } else if ("COMPLETE" == trigger.status) {
                        completeCount++;
                    } else if ("AWAIT" == trigger.status) {
                        awaitCount++;
                    } else {
                        waiteCount++;
                    }
                }
                failedCount += jobInfo.failedCount;
                successCount += jobInfo.successCount;
            }
        }
        allCount = rows.length;
        $this.find(".tempo-task-complete").val("全部" + allCount);
        var startSucceedCountArr = [];
        var startSucceedCount = 0;
        var unstart = 0;
        var starting = 0;
        var iftrue = " ";
        for (i = 0; i < rows.length; i++) {
            iftrue = rows[i].ASY_SERVIECESTATE;
            if (iftrue == "RUNNING") {
                startSucceedCount++;
            } else if (iftrue == "STARTING") {
                starting++;
            } else {
                unstart++;
            }
        }
        $this.find(".tempo-task-startSucceed").val("已启动" + startSucceedCount);
        //$this.find(".tempo-task-running").val("启动中");
        $this.find(".tempo-task-starting").val("启动中" + starting);
        $this.find(".tempo-task-unstart").val("未启动" + unstart);

        //22463 挖掘-成果监测-成果列表：IE11浏览器下调度状态可以点击，点击时有交互状态，统计数据不需要有交互状态，不可点击
        // $this.find(".tempo-task-complete").attr("disabled",true);
        // $this.find(".tempo-task-complete").attr("disabled",true);
        $this.find(".state_succ_bt").attr("disabled", true);
        $this.find(".state_fail_bt").attr("disabled", true);
        $this.find(".tempo-task-waite").attr("disabled", true);
        $this.find(".tempo-task-running").attr("disabled", true);
        $this.find(".tempo-task-pause").attr("disabled", true);
        $this.find(".tempo-task-succeed").attr("disabled", true);
        $this.find(".tempo-task-failed").attr("disabled", true);
    }

    /**
     * 校验表单
     */
    var validateForm = function (dialog, isEdit, oldName) {
        var v = dialog.find('form').formValidate();
        var jobconfig = TempoUtils.getRecord(dialog.find('form'));
        var triggerName = jobconfig.name;
        if (oldName != triggerName && isEdit) {
            var isRaname = false;
            $.ajax({
                url: contextPath + '/api/ai/mine/publish/listAllTriggerName',
                type: 'post',
                async: false,
                success: function (triggerNames) {
                    if (triggerNames) {
                        isRaname = triggerNames.indexOf(triggerName) > -1;
                    }
                }
            });
            if (isRaname) {
                $("<div/>").alert({msg: TempoUtils.locale("mine.tasknameerror"), height: 180});
                return false;
            }
        }
        return v && (function () {
            console.log(jobconfig);
            if (jobconfig.starttime && jobconfig.endtime) {
                var s = new Date(jobconfig.starttime);
                var e = new Date(jobconfig.endtime);
                if (s.getTime() > e.getTime()) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.shengxiaoshijianerror"), height: 180});
                    return false;
                }
            }
            if (jobconfig.stime && jobconfig.etime) {
                if (jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.kaishishijianerror"), height: 180});
                    return false;
                }
                if (jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height: 180});
                    return false;
                }
            }
            return true;
        })();
    }

    var getCheckRowDatas = function () {
        var gridTable = $this.find('#mine-opt-job-grid');
        var checkedRowIds = gridTable.datagrid("getCheckedRowIds");
        if (checkedRowIds.length == 0) {
            $("<div/>").alert({msg: "未选择批量操作的任务！", height: 180});
            return false;
        } else {
            var lastEditId = gridTable.datagrid("getLastEditId");
            if (lastEditId) {
                gridTable.datagrid("saveRow", lastEditId);
            }
            var checkedRowDatas = [];
            var allRowDatas = gridTable.datagrid("getRowData");
            for (var i = 0; i < checkedRowIds.length; i++) {
                for (var j = 0; j < allRowDatas.length; j++) {
                    if (checkedRowIds[i] == allRowDatas[j].id) {
                        var rowData = allRowDatas[j];
                        var successSpan = rowData["trigger.status"].split("：")[1];
                        var failedSpan = rowData["trigger.status"].split("：")[1];
                        //获取成功次数
                        var successCount = Number(successSpan.substring(0, successSpan.indexOf("次")));
                        //获取失败次数
                        var failedCount = Number(failedSpan.substring(0, failedSpan.indexOf("次")));
                        checkedRowDatas.push({
                            id: rowData.id,
                            triggerId: rowData.jobId,
                            logNum: successCount + failedCount
                        });
                    }
                }
            }
            return checkedRowDatas;

        }
    }

    var initOrrefresh = function (isReloadGrid) {
        if ($this.find('.view-container').height() - 98 > 0) {
            $this.find('.publish_tab').height($this.find('.view-container').height() - 98)
        }
        if (isReloadGrid !== false) {
            initJobGrid();
        }
        // $(".ui-common-table").css("width", "100%");
        $(".ui-paging-info").hide();
        if (allDatas.length == 0) {
            $(".tempo-message").css("display", "");

        } else {
            $(".tempo-message").css("display", "none");
        }
        //$(".ui-paging-info").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-totempo'></span>");
        var form = $this.find('.queryJobSchedulingForm').css("display", "block");
        TempoUtils.parserUi(form, {});
        form.find('[name="starttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="endtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="endtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        }).css("width", "100px");
        form.find('[name="endtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="starttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="starttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        }).css("width", "100px");
        //判断当筛选框里是否有值，如没值就将蓝点隐藏
        var if_to_hide = function () {
            // 获取筛选div里的搜索input框
            var inputs = $('#shaixuanDiv').find('input');
            // 定义是否有数据标识 true表示有数据
            var hasValue = false;
            for (var i = 0; i < inputs.length; i++) {
                if (inputs.eq(i).val().trim() != "") {
                    hasValue = true;
                    break;
                }
            }
            // 如果搜索框中有值，则显示图标
            if (hasValue) {
                $("#ifshaixuan").removeAttr('style');
                $(".sizer-reset").css("color", "#5185e4")
            } else {
                $("#ifshaixuan").hide();
            }
        }
        form.find('[name="laststarttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="lastendtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="lastendtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
                if_to_hide();
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                //$.datepicker._hideDatepicker(this);
                if_to_hide();
            }
        }).css("width", "100px");
        form.find('[name="lastendtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
                if_to_hide();
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="laststarttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="laststarttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                //$.datepicker._hideDatepicker(this);
                if_to_hide();
            }
        }).css("width", "100px");

        form.find('[name="createStartTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                width: 50,
                onClose: function (selectedDate) {
                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createEndTime"]').datepicker(
                            "option", "minDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createEndTime"]').datepicker(
                        "option", "minDate", d2str);
                },
                onSelect: function (value) {
                    // connectChart();
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    $.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        form.find('[name="createEndTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                onSelect: function (value) {
                },
                onClose: function (selectedDate) {
                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createStartTime"]').datepicker(
                            "option", "maxDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createStartTime"]').datepicker(
                        "option", "maxDate", d2str);
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    $.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        //筛选框查询操作
        $('.queryBtn').button({

            emphasize: true,
        }).css("width", "60px");
        form.find('.resetBtn').button({
            emphasize: true,
        }).css("width", "60px");

        form.find('.task-opts-btn').button({
            emphasize: true,
            click: function (e) {
            }
        });

        form.find('.task-opts-btn').on("mouseover", function (event) {
            var offset = $(this).offset();
            form.find("#tempo-header-task-opts-infos").css({
                left: offset.left,
                top: offset.top + 26
            });
            form.find("#tempo-header-task-opts-infos").show();
        });

        form.find('.task-opts-btn').on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();

        });

        form.find("#tempo-header-task-opts-infos").on("mouseover", function () {
            form.find("#tempo-header-task-opts-infos").show();

        })
        form.find("#tempo-header-task-opts-infos").on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();
        })

        form.find("#tempo-header-task-opts-start-flow").on("click", function (e) {
            var checkedRowDatas = getCheckRowDatas();
            if (checkedRowDatas == false) {
                return;
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + seleccount + "个任务，是否确定批量手动执行？",
                ok: function () {
                    if (checkedRowDatas != null && checkedRowDatas != false) {
                        var process = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: contextPath + '/api/ai/app/schedule/job/batchmanual',
                            type: 'post',
                            data: {
                                batchdata: JSON.stringify(checkedRowDatas)
                            },
                            dataType: 'json',
                            success: function (obj) {
                                process.tempoprogressbar("destroy");
                                var data = obj.data;
                                if (data && data.length > 0) {
                                    if (obj.success) {
                                        $("<div/>").alert({msg: "任务" + data.join(",") + "正在执行中，请稍后再试", height: 180});
                                    }
                                }
                                $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            }, error: function (obj) {
                                process.tempoprogressbar("destroy");
                            }
                        });
                    }
                }
            });
        });

        form.find("#tempo-header-task-opts-stop-flow").on("click", function (e) {
            var checkedRowDatas = getCheckRowDatas();
            if (checkedRowDatas == false) {
                return;
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + checkedRowDatas.length + "个任务，是否确定批量停止执行？",
                ok: function () {
                    if (checkedRowDatas != null && checkedRowDatas != false) {
                        var process = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: contextPath + '/api/ai/app/schedule/job/batchstop',
                            type: 'post',
                            data: {
                                batchdata: JSON.stringify(checkedRowDatas),
                            },
                            dataType: 'json',
                            success: function (obj) {
                                if (obj.success) {
                                    $("<div/>").alert({msg: TempoUtils.locale("mine.publish-job-killed"), height: 180});
                                } else {
                                    $("<div/>").alert({
                                        msg: TempoUtils.locale("mine.publish-job-notexists"),
                                        height: 180
                                    });
                                }
                                process.tempoprogressbar("destroy");
                                $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            }, error: function (obj) {
                                process.tempoprogressbar("destroy");
                            }
                        });
                    }
                }
            });
        });

        form.find("#tempo-header-task-opts-pause-task").on("click", function (e) {
            var checkedRowDatas = getCheckRowDatas();
            if (checkedRowDatas == false) {
                return;
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + checkedRowDatas.length + "个任务，是否确定批量暂停执行？",
                ok: function () {
                    if (checkedRowDatas != null && checkedRowDatas != false) {
                        var process = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: contextPath + '/api/ai/app/schedule/job/batchpause',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                batchdata: JSON.stringify(checkedRowDatas)
                            },
                            success: function (obj) {
                                process.tempoprogressbar("destroy");
                                var data = obj.data;
                                if (data && data.length > 0) {
                                    if (obj.success) {
                                        $("<div/>").alert({msg: "任务" + data.join(",") + "已经失效不允许暂停", height: 180});
                                    }
                                }
                                $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                            }, error: function (obj) {
                                process.tempoprogressbar("destroy");
                            }
                        });
                    }
                }
            });
        });

    }
    var isAlive = function (uid) {

        var id = uid;
        $.postForm({
            url: contextPath + '/api/ai/app/model/status/' + id,
            success: function (rp) {

                //fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data);
            }
        });
    }

    var openViewDetailDialog = function (job) {
        var paramDialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'app-flow-scheduling-execute-detail');
        var parentDiv = $this.find("#jobContainer");
        paramDialog.dialog({
            title: "服务详情",
            width: $this.width(),
            height: $this.height(),
            resizable: false,
            modal: true,
            close: function () {
                paramDialog.dialog('destroy');
            },
            open: function () {
                $m.loadPage(contextPath + "/api/ai/app/statistics/service_view", $(this), job.SERVICEID, {"data": job});
                $(".ui-dialog-title").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-leftarrows-undertint tempo-leftback' style='float: left;margin-top: 12px;'></span>")
                $("#app-flow-scheduling-execute-detail").prev().find("button").css("display", "none")
                $(".ui-draggable-handle").css("cursor", "auto");
                $(".tempo-leftback").css("cursor", "pointer");
                Eventbus.trigger('updateStatusLoop.service', job.FLOWID, null, "sync");
                $(".tempo-leftback").click(function () {
                    clearInterval(window.publishTaskStatusInterval);
                    paramDialog.dialog('destroy');
                    // 请求服务是否存活
                    // isAlive(job.SERVICEID);
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    $(".after_select").hide();

                    setTimeout(function () {
                        for (var i = 0; i < 3; i++) {
                            that.grid.setGridParam({loadui: false}).trigger("reloadGrid");

                        }
                    }, 2000);

                });
            }

        });
    }

    var showDetail = function (paramDialog, flowId, job, idx, jobId) {
        var analyseStatus = TempoMineUtils.analyseStatus;
        var bindEvent = function () {
            Eventbus.bind("getAnalyseStatus", function () {
                return analyseStatus;
            });
        }
        bindEvent();
        analyseStatus.setType("viewing");
        var parentDivHeight = paramDialog.height();

        analyseStatus.setMainId(flowId);
        paramDialog.find('#tempo-mine-viewing').layout({
            north: {
                resizable: false,
                size: parentDivHeight * 0.95,
                spacing_open: 0
            },
            center: {
                onresize_end: function () {

                }
            }
        });
        $.getQuery({
            url: contextPath + '/api/ai/node/library',
            success: function (sp) {
                var data = sp.data;
                load(data, flowId, job, idx, jobId);
            }
        });
    }

    var load = function (data, flowId, job, idx, jobId) {
        window.apiInsight = 'inline';
        var alg = data.alg;
        window[window.constant.MNODES] = {};
        // 将获取的所有算法节点保存到页面window对象中
        window[window.constant.DATAMINE_COMMONOPER] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_COMMONOPER]);
        window[window.constant.DATAMINE_TYP] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_TYP]);
        window[window.constant.DATAMINE_PRE] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_PRE]);
        window[window.constant.DATAMINE_DATA] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DATA]);
        window[window.constant.DATAMINE_CONTROL] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CONTROL]);
        window[window.constant.DATAMINE_CHART] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CHART]);
        window[window.constant.DATAMINE_ALG] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_ALG]);
        window[window.constant.DATAMINE_EXTEND] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_EXTEND]);
        window[window.constant.DATAMINE_MODEL] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_MODEL]);
        window[window.constant.USER_DEFINED] = TempoPluginUtils
            .pluginExtend(alg[window.constant.USER_DEFINED]);
        window[window.constant.DATAMINE_FUNSION] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_FUNSION]);
        window[window.constant.DATAMINE_FEATUREENG] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_FEATUREENG]);
        window[window.constant.DATAMINE_STATISTICS] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_STATISTICS]);
        window[window.constant.DATAMINE_DEEPLEARNING] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DEEPLEARNING]);
        window[window.constant.DATAMINE_INTEGRATED] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_INTEGRATED]);
        window[window.constant.DATAMINE_AUTO] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_AUTO]);
        window[window.constant.DATAMINE_CF] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_CF]);
        window[window.constant.DATAMINE_TEXTMINING] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_TEXTMINING]);

        window[window.constant.DATAMINE_DEFAULT] = TempoPluginUtils
            .pluginExtend(alg[window.constant.DATAMINE_DEFAULT]);


        //新增分类处理
        for (var i in window[window.constant.DATAMINE_DEFAULT]) {
            var key = window[window.constant.DATAMINE_DEFAULT][i]
            var eleObject = new Object();
            eleObject[i] = window[window.constant.DATAMINE_DEFAULT][i];
            window[key.type] = eleObject
        }
        // 将国际化字典保存
        var i18ns = data[window.constant.I18NDICT];
        for (var i in i18ns) {
            TempoUtils.locale(i, i18ns[i]);
        }
        var groupCategory = function (eles) {
            for (var p in eles) {
                var ele = eles[p];
                window[window.constant.MNODES][ele.id] = ele;
                ele.title = ele.name;
                var icon = 'ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-library-unselect';
                ele.icon = icon;
                if (ele.libraryIcon) {
                    ele.icon += " tempo-mine-library-node-" + ele.id;
                }

            }
        }
        groupCategory(window[window.constant.DATAMINE_COMMONOPER]);
        groupCategory(window[window.constant.DATAMINE_TYP]);
        groupCategory(window[window.constant.DATAMINE_PRE]);
        groupCategory(window[window.constant.DATAMINE_DATA]);
        groupCategory(window[window.constant.DATAMINE_CONTROL]);
        groupCategory(window[window.constant.DATAMINE_CHART]);
        groupCategory(window[window.constant.DATAMINE_ALG]);
        groupCategory(window[window.constant.DATAMINE_EXTEND]);
        groupCategory(window[window.constant.DATAMINE_MODEL]);
        groupCategory(window[window.constant.USER_DEFINED]);
        groupCategory(window[window.constant.DATAMINE_FUNSION]);
        groupCategory(window[window.constant.DATAMINE_FEATUREENG]);
        groupCategory(window[window.constant.DATAMINE_STATISTICS]);
        groupCategory(window[window.constant.DATAMINE_DEEPLEARNING]);
        groupCategory(window[window.constant.DATAMINE_INTEGRATED]);
        groupCategory(window[window.constant.DATAMINE_AUTO]);
        groupCategory(window[window.constant.DATAMINE_CF]);
        groupCategory(window[window.constant.DATAMINE_TEXTMINING]);
        groupCategory(window[window.constant.PROTOCOL_RESOLUTION]);
        groupCategory(window[window.constant.TARGET_RECOGNITION]);
        groupCategory(window[window.constant.TOPOLOGICAL_ANALYSIS]);
        groupCategory(window[window.constant.VULNERABILITY_ANALYSIS]);
        groupCategory(window[window.constant.AGGRESIVE_BEHAVIOR_ANALYSIS]);
        groupCategory(window[window.constant.ENCRYPTED_DATA_ANALYSIS]);

        ScheduleMineViewlingController(flowId, false, job, idx, jobId);
    }

    initOrrefresh();

    //初始化成果管理页面页面变动监听事件
    var timeout = 0;
    window.addEventListener('resize', function () {
        if (timeout != 0) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function () {
            that.grid.datagrid("reloadGrid");
            //调整弹框宽度
            if ($this.find("#app-flow-scheduling-execute-detail").length > 0) {
                $this.find("#app-flow-scheduling-execute-detail").parent().css("width", $this.width());
                if ($this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li").length > 0) {
                    var tempoHeadLis = $this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li");
                    for (var i = 0; i < tempoHeadLis.length; i++) {
                        var $tempoHeadLi = $(tempoHeadLis[i]);
                        if ($tempoHeadLi.css("border-bottom") == '2px solid rgb(31, 115, 182)') {
                            //触发选中页签的点击事件，重新触发页面样式
                            $tempoHeadLi.trigger("click");
                            break;
                        }
                    }
                }
            }
            timeout = 0;
        }, 200)
    });
});